<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <!--用户数据-->
      <el-col :span="24" :xs="24" class="div-height-left">
        <el-row>
          <el-col :span="7">
            <div class="search-container">
              <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
                <el-form-item v-if="!userInfo.orgId" label="机构" prop="orgId" style="width: 47%">
                  <select-org-tree class="width-120" :value="queryParams.orgId" @orgNodeClick="orgNodeClick" />
                </el-form-item>
                <el-form-item label="类型名称" prop="name" style="width: 40%">
                  <el-input v-model="queryParams.name" clearable placeholder="请输入类型名称"
                    @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item style="width: 100%">
                  <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                </el-form-item>
              </el-form>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPerm="['base:examType:add']" plain type="primary" @click="handleAdd"><template
                    #icon><i-ep-plus /></template>新增类型
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button plain type="info" @click="toggleExpandAll"><template #icon><i-ep-sort /></template>展开/折叠
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button plain type="danger" @click="refreshCacheExamTypeFun"><template #icon> <i-ep-refresh />
                  </template>刷新缓存
                </el-button>
              </el-col>
            </el-row>

            <el-table v-if="refreshTable" v-adaptive="40" :data="examTypeList" :default-expand-all="isExpandAll"
              highlight-current-row :header-cell-style="$headerCellStyle"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :border="true" row-key="examTypeId"
              stripe style="overflow-y: auto" @row-click="rowClick">
              <el-table-column :show-overflow-tooltip="true" label="类型名称" prop="name" width="130px" />
              <!--            <el-table-column label="执行科室" :align="'center'" prop="performedBy"/>-->
              <el-table-column :align="'center'" label="级别" prop="level" width="70px" />
              <!--                    <el-table-column label="备注信息" width="100px" :align="'center'" prop="remarks"/>-->
              <el-table-column :align="'center'" label="排序" prop="sort" width="70px" />
              <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                min-width="100px">
                <template #default="scope">
                  <el-button v-hasPerm="['base:examType:edit']" type="success"
                    @click.stop="handleUpdate(scope.row)"><template #icon><i-ep-edit /></template>修改
                  </el-button>
                  <el-button v-hasPerm="['base:examType:add']" type="primary"
                    @click.stop="handleAdd(scope.row)"><template #icon><i-ep-plus /></template>新增
                  </el-button>
                  <el-button v-hasPerm="['base:examType:remove']" type="danger"
                    @click.stop="handleDelete(scope.row)"><template #icon><i-ep-delete /></template>删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="17">
            <exam-vs-clinic ref="examVsClinicRef" :org-id="queryParams.orgId" />
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 添加或修改检查项目类型exam_type对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="examTypeOptions" :render-after-expand="false" check-strictly
            filterable placeholder="类型选择" style="width: 100%" />
        </el-form-item>
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <!--                <el-form-item label="执行科室" prop="performedBy">-->
        <!--                    <el-input v-model="form.performedBy" placeholder="请输入执行科室"/>-->
        <!--                </el-form-item>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="级别" prop="level">
              <el-input v-model="form.level" disabled placeholder="请输入级别" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
    addExamType,
    delExamType,
    getExamType,
    listExamType,
    refreshCacheExamType,
    updateExamType,
} from "@/api/base/examType";
import examVsClinic from "@/views/base/examType/examVsClinic.vue";
import {useUserStoreHook} from "@/store/modules/user";

const useUserStore = useUserStoreHook();
const { proxy } = getCurrentInstance() as any;
const formRef = ref();
const examVsClinicRef = ref();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 按钮loading
const buttonLoading = ref(false);
// 下拉框机构树
const orgOptions = ref([]);
// 显示搜索条件
const showSearch = ref(true);
// 检查项目类型exam_type表格数据
const examTypeList = ref([]);
// 检查项目类型exam_type树选项
const examTypeOptions = ref<any>([]);
// 检查类型list（无父子结构）
const typeList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 是否展开，默认全部展开
const isExpandAll = ref(true);
// 重新渲染表格状态
const refreshTable = ref(true);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref({
  name: "",
  orgId: "",
  performedBy: "",
  // sort: 0,
  // level: 0,
  parentId: "",
  parentIds: "",
  remarks: "",
});
// 表单参数
const form = ref<any>({});
// 表单校验
const rules = ref({
  name: [
    {
      required: true,
      message: "类型名称不能为空",
      trigger: "blur",
    },
  ],
  orgId: [
    {
      required: true,
      message: "机构ID不能为空",
      trigger: "blur",
    },
  ],
  sort: [
    {
      required: true,
      message: "排序不能为空",
      trigger: "blur",
    },
  ],
  level: [
    {
      required: true,
      message: "级别不能为空",
      trigger: "blur",
    },
  ],
});

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
  getList();
}
/** 查询检查项目类型exam_type列表 */
function getList() {
  listExamType(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    examTypeList.value = proxy.$handleTree(
      response.data,
      "examTypeId",
      "parentId"
    );
  });
}
// 机构树点击事件
function orgNodeClick(data, _e) {
  queryParams.value.orgId = data.orgId;
  if (queryParams.value.orgId) {
    getList();
  }
}
function refreshCacheExamTypeFun() {
  refreshCacheExamType().then((res: any) => {
    ElMessage.success(res.msg);
  });
}
/** 查询检查项目类型exam_type下拉树结构 */
function getTreeselect() {
  listExamType({ orgId: queryParams.value.orgId }).then((response: any) => {
    examTypeOptions.value = [
      {
        examTypeId: 0,
        label: "顶级节点",
        value: 0,
        name: "顶级节点",
        children: proxy.$handleTree(response.data, "examTypeId", "name"),
        level: "0",
      },
    ];
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    examTypeId: null,
    name: null,
    orgId: queryParams.value.orgId,
    performedBy: null,
    sort: null,
    level: null,
    parentId: null,
    parentIds: null,
    delFlag: null,
    createBy: null,
    updateBy: null,
    remarks: null,
  };
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.examTypeId) {
    form.value.parentId = row.examTypeId;
    form.value.level = Number(row.level) + 1;
  } else {
    form.value.parentId = 0;
    form.value.level = 1;
  }
  open.value = true;
  title.value = "添加检查项目类型";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getTreeselect();
  getExamType(row.examTypeId).then((response) => {
    form.value = response.data;
    if (row != null) {
      form.value.parentId = row.parentId;
    }
    open.value = true;
    title.value = "修改检查项目类型";
  });
}
/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      let index = typeList.value.findIndex((item: any) => {
        return item.name === form.value.name;
      });
      // if (
      //   (index > -1 &&
      //     form.value.examTypeId !== typeList.value[index].examTypeId) ||
      //   (index > -1 && !form.value.examTypeId)
      // ) {
      //   buttonLoading.value = false;
      //   return ElMessage.error("类别名称已存在，请重新修改类别名称");
      // }
      if (form.value.examTypeId != null) {
        updateExamType(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addExamType(form.value)
          .then((_response) => {
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let type = true;
  let index = examTypeList.value.findIndex((item: any) => {
    return row.examTypeId === item.examTypeId;
  });
  if (index > -1) {
    if (examTypeList.value[index].children.length > 0) {
      type = false;
    }
  }
  ElMessageBox.confirm(
    '是否确认删除检查项目类型名称为"' + row.name + '"的数据项？',
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      if (type) {
        delExamType(row.examTypeId).then(() => {
          if (type) {
            getList();
            ElMessage.success("删除成功");
          } else {
            type = true;
            return ElMessage.error("此类别存在子项目，不能删除");
          }
        });
      }
    })
    .catch(() => {
    });
}
/** 类别列表行点击事件 */
function rowClick(row) {
  if (row.level === 1) {
    return ElMessage.error("顶级类别不能增加、查看项目，请选择下级类型");
  }
  // 调用项目页面查询方法
  examVsClinicRef.value.init(row, typeList.value);
}
</script>
<script lang="ts">
export default {
  name: "ExamType",
};
</script>
